"""强制停止所有后端进程"""
import subprocess
import time

print("Stopping all backend processes...")

# 获取所有在8000端口的进程
result = subprocess.run(
    'netstat -ano | findstr :8000 | findstr LISTENING',
    shell=True,
    capture_output=True,
    text=True
)

pids = set()
for line in result.stdout.strip().split('\n'):
    if line:
        parts = line.split()
        if len(parts) >= 5:
            pid = parts[-1]
            pids.add(pid)

print(f"Found {len(pids)} processes on port 8000")

for pid in pids:
    print(f"Killing PID {pid}...")
    subprocess.run(f'taskkill /F /PID {pid}', shell=True, capture_output=True)

time.sleep(3)

# 验证
result = subprocess.run(
    'netstat -ano | findstr :8000 | findstr LISTENING',
    shell=True,
    capture_output=True,
    text=True
)

if result.stdout.strip():
    print("WARNING: Some processes still running")
    print(result.stdout)
else:
    print("SUCCESS: All backend processes stopped")
